package cn.com.lsy.product.lepao.controller.base;

import cn.com.lsy.product.lepao.model.entities.LpAdminTbl;
import cn.com.lsy.product.lepao.model.entities.LpSessionTbl;
import cn.com.lsy.product.lepao.service.IAdminService;
import cn.com.lsy.product.lepao.service.ISessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
public class BaseController {
    @Autowired
    private HttpServletRequest request;

    // 用户信息
    public static LpAdminTbl userInfo;

    @Autowired
    protected IAdminService iAdminService;
    @Autowired
    protected ISessionService iSessionService;

    private static BaseController serverHandler;

    @PostConstruct // 通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        serverHandler = this;
        serverHandler.iAdminService = this.iAdminService;
        serverHandler.iSessionService = this.iSessionService;
        // 初使化时将已静态化的testService实例化
    }

    /**
     * 获取token
     *
     * @return
     */
    protected String getToken() {
        return request.getHeader("token");
    }

    /**
     * 获取角色类型
     *
     * @return
     */
    protected String getRoleType() {
        return request.getHeader("roleType");
    }

    /**
     * 获取用户信息
     *
     * @param
     * @return
     */
    public LpAdminTbl getUserInfo(String token, String roleType) {

        // 获取session信息
        List<LpSessionTbl> sessionInfo = serverHandler.iSessionService.selectInfoByToken(token, roleType);
        if (sessionInfo.size() > 0) {

            // 获取用户信息
            userInfo = serverHandler.iAdminService.selectUserInfoById(sessionInfo.get(0).getrId());
            if (userInfo != null) {

                return userInfo;

            } else {
                return null;
            }

        } else {
            return null;
        }
    }

    /**
     * 验证参数是否合法
     *
     * @param result
     */
    public static void checkParam(BindingResult result) {

        if (result.hasErrors()) {
            result.getAllErrors().stream().forEach(error -> {
                FieldError fieldError = (FieldError) error;
                throw new RuntimeException(fieldError.getDefaultMessage());
            });
        }
    }


    /**
     * 获取用户id
     *
     * @return
     */
    public int getUserId() {

        int userId = 0;

        if (userInfo != null) {

            userId = userInfo.getId();
        }

        return userId;
    }

}
